package lbim.client.ui;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;

import de.enough.polish.ui.TreeItem;
import de.enough.polish.util.Locale;

import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TabbedForm;
import de.enough.polish.ui.UiAccess;
import de.enough.polish.util.StringTokenizer;
import lbim.client.main.ChatListener;

/**
 *
 * @author tharindu
 */
public class TabbedScreen extends TabbedForm implements CommandListener, ChatListener, ItemStateListener {

    private MainUI ui_;
    private Hashtable commands_;

    private TreeItem tree;
    private StringItem sichats;

    private Image rhtImg;
    private Image offImg;
    private Image chatImg;
    private Image pendingImg;
    
    private Vector chats;
    
    private Command cmdSend = new Command("Send", Command.OK, 1);
    private Command cmdContacts = new Command("Contacts", Command.BACK, 1);

    public TabbedScreen() throws IOException {
        //#style tabbedForm
        super(Locale.get("tabbed.title"), new String[]{Locale.get("tabbed.contacts")} , new Image[]{Image.createImage("/chat.png")}); //[LOCALE]

        ui_ = MainUI.getInstance();
        commands_ = ui_.getCommands();
        //#style accountTree
        tree = new TreeItem(null);
        chats = new Vector();
        try {
            setCommandListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        addCommand((Command) commands_.get(new Integer(MainUI.CMD_LOGOUT)));
        addCommand((Command) commands_.get(new Integer(MainUI.CMD_MAP)));
        rhtImg = Image.createImage("/right.png");
        offImg = Image.createImage("/left.png");
        chatImg = Image.createImage("/person.png");
        pendingImg = Image.createImage("/chat2.png");
        append(0,tree);
    }

    public void resetUi(String presenceList) throws IOException{
        tree.removeAll();
        //#style accounts
        Item onlinenode = tree.appendToRoot(Locale.get("tree.onlinenode"), Image.createImage("/available.png"));
        //#style accounts
        Item offlinenode = tree.appendToRoot(Locale.get("tree.offlinenode"), Image.createImage("/invisible.png"));
        StringTokenizer t = new StringTokenizer(presenceList, ",");
        String s; int i; int j; Item tmpitm;
        while(t.hasMoreTokens()) {
            s = t.nextToken();
            i = s.indexOf(":"); j = i+1;
            if(s.substring(j).equals("ONLINE")) {
                //#style contacts
                tmpitm = tree.appendToNode(onlinenode, " " + s.substring(0, i), rhtImg);
                tmpitm.addCommand(new Command("Chat " + s.substring(0, i), "Chat", Command.OK, 1));
            } else {
                //#style contacts
                tmpitm = tree.appendToNode(offlinenode, " " + s.substring(0, i), offImg);
                tmpitm.addCommand(new Command("Chat " + s.substring(0, i), "Chat", Command.OK, 1));
            }
        }
    }


    public void commandAction(Command c, Displayable d) {
        if(c.getLongLabel() == "Chat") {

            String contact = c.getLabel();
            contact = contact.substring(5, contact.length());
            System.out.println("[TabbedScreen] contact :" + contact);

            // if contact online
            if(tree.getFocusedIndex() == 0) {
                if(chats.contains(contact)) {
                    int tab = chats.indexOf(contact);
                    System.out.println("[TabbedScreen] CHAT TAB AVAILABLE");
                    setActiveTab((tab+1));
                } else {
                    System.out.println("[TabbedScreen] CHAT TAB NOT AVAILABLE");
                    int tab = addNewTab(contact, chatImg);
                    chats.addElement(contact);
                    //#style itemTextInput
                    TextField tf_ = new TextField("", "", 200, TextField.ANY);
                    append(tab, tf_);
                    UiAccess.setItemStateListener(tf_, this);
                    tf_.addCommand(cmdSend);
                    tf_.addCommand(cmdContacts);
                    setActiveTab(tab);
                }
            } else {
                ui_.setAlert("Contact is Offline", this);
            }
        } else if (c == cmdSend) {
            System.out.println("[TabbedScreen] send button");
            int tab = getActiveTab();
            System.out.println("tab: " + tab);
            String contact = (String) chats.elementAt((tab-1));
            System.out.println("contact: " + contact);
            String message = ((TextField) this.get(tab, 0)).getString();
            if (message.length() > 0) {
                //#style myChats
                sichats = new StringItem("> " + message, null);
                this.insert(1, sichats);
                ui_.sendMessage(contact, message);
                ((TextField) this.get(tab, 0)).setString(null);
            }
            ((TextField) this.get(tab, 0)).notifyStateChanged();
        } else if (c == cmdContacts) {
            setActiveTab(0);
        } else {
            MainUI.hsenidCommand(c, d);
        }
    }

    public void messageReceived(String sender, String message) {
        System.out.println("[TabbedScreen] messageReceived() sender: " + sender + " message: " + message);
        if(chats.contains(sender)) {
            int tab = chats.indexOf(sender) + 1;
            //#style buddyChats
            sichats = new StringItem("> " + message, null);
            this.setActiveTab(tab);
            this.insert(1, sichats);
        } else {
            int tab = addNewTab(sender, chatImg);
            chats.addElement(sender);
            //#style itemTextInput
            TextField tf_ = new TextField("", "", 200, TextField.ANY);
            append(tab, tf_);
            tf_.addCommand(cmdSend);
            tf_.addCommand(cmdContacts);
            UiAccess.setItemStateListener(tf_, this);
            setActiveTab(tab);
            //#style buddyChats
            sichats = new StringItem("> " + message, null);
            this.setActiveTab(tab);
            this.insert(1, sichats);
        }
    }

    public void itemStateChanged(Item item) {
        String message = ((TextField) this.get(this.getActiveTab(), 0)).getString();
        if(message.length() > 0) {
            setTabImage(getActiveTab(), pendingImg);
        } else {
            setTabImage(getActiveTab(), chatImg);
        }
    }
}
